<?php

namespace services\patient;

use common\models\clinic\Clinic;
use common\models\member\Attr;
use common\models\member\Member;
use Yii;
use common\components\Service;
use common\models\patient\User;

/**
 * Class UserService
 * @package services\patient
 */
class UserUpdateService extends Service
{
    /**
     * @return void
     */
    public function updateMemberBatch()
    {
        // 按诊室查询医助
        $memberList = Attr::find()
            ->alias('a')
            ->select(['GROUP_CONCAT(a.member_id) member_arr', 'a.clinic_id'])
            ->innerJoin(Member::tableName() . ' m', 'm.id = a.member_id and m.status = '. Member::STATUS_ENABLE)
            ->leftJoin(Clinic::tableName() . ' c', 'c.id = a.clinic_id and c.status = '. Clinic::STATUS_ENABLE)
            ->where(['c.project_id' => 9])
            ->groupBy(['a.clinic_id'])
            ->asArray()
            ->all();

        foreach ($memberList as $ml) {
            // 同个诊室下的患者
            $data = User::find()
                ->select(['id', 'belong_assistant_id'])
                ->where(['project_id' => 9, 'status' => User::STATUS_ENABLE, 'clinic_id' => $ml['clinic_id']])
                ->asArray()
                ->all();
            $mlMemberArr = explode(',', $ml['member_arr']);
            $clinicMemberNum = count($mlMemberArr);
            if (!$clinicMemberNum) {
                return;
            }
            $arr = [];
            foreach ($data as $kval => $val) {
                // 取余数
                $yushu = $kval % $clinicMemberNum;
                for ($i = 0; $i <= $yushu; $i++) {
                    if ($yushu == $i) {
                        // 批量的患者ID
                        $arr[$i][] = $val['id'];
                    }
                }
            }
            foreach ($arr as $ka => $a) {
                User::updateAll(['belong_assistant_id' => $mlMemberArr[$ka]], ['id' => $a]);
            }
        }
    }
}